package com.ssy.invoicing.order.service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ssy.invoicing.common.util.DateUtil;
import com.ssy.invoicing.common.util.StringUtil;
import com.ssy.invoicing.dao.support.BaseSqlDao.SplitPageResult;
import com.ssy.invoicing.order.bean.SaleOrderBean;
import com.ssy.invoicing.order.bean.SaleProductBean;
import com.ssy.invoicing.order.bean.vo.OrderVo;
import com.ssy.invoicing.order.dao.OrderDao;

@Service(value="orderService")
@Transactional
public class OrderService {
    private static Logger LOG = LoggerFactory.getLogger(OrderService.class);
    
    @Resource(name="orderDao")
    private OrderDao orderDao;
    
    /**
     * 根据条件查询订单列表
     * @param vo
     * @return
     * @throws SQLException
     */
    public SplitPageResult queryOrderList(OrderVo vo) throws SQLException {
        return orderDao.queryOrderList(vo.initParams(), vo.getPage());
    }
    
    /**
     * 查询没有生成采购订单的销售列表
     * @param vo
     * @return
     * @throws SQLException
     */
    public List<SaleOrderBean> queryOrderListNoPurchase(OrderVo vo) throws SQLException {
        return orderDao.queryOrderListNoPurchase(vo.initParams());
    }

    /**
     * 创建销售订单
     * @author suoyao.shen
     * @param order
     * @param saleProductList
     * @return
     */
    public int saveOrder(SaleOrderBean order, String[] pname, String[] pattern,
                         Integer[] saleCount, String[] salePrice, String[] totalPrice,
                         Date[] deliverTime, String[] remark) {
        SaleOrderBean orderBean = orderDao.saveOrder(order);
        
        List<SaleProductBean> productList = new ArrayList<SaleProductBean>();
        for (int i = 0; i < pname.length; i++) {
            productList.add(new SaleProductBean(pname[i], pattern[i], saleCount[i], salePrice[i],
                    totalPrice[i], deliverTime[i], remark[i],orderBean.getId()));
        }
        saveProductBatch(productList);
        return orderBean.getId();
    }
    
    /**
     * 根据销售订单加载产品
     * @author suoyao.shen
     * @param orderId
     * @return
     */
    public List<SaleProductBean> loadProductByOrderId(Integer orderId) {
        List<SaleProductBean> productList = orderDao.loadProductByOrderId(orderId);
        if (productList == null || productList.isEmpty()) {
            return new ArrayList<SaleProductBean>();
        }
        //这里循环产品列表,汇总产品数量和价格
        int count = 0;
        long price = 0l;
        for (SaleProductBean product : productList) {
            count += product.getSaleCount().intValue();
            price += Long.valueOf(product.getTotalPrice());
        }
        SaleProductBean p = new SaleProductBean();
        p.setPname("汇总");
        p.setSaleCount(count);
        p.setTotalPrice(String.valueOf(price));
        productList.add(p);
        return productList;
    }
    
    /**
     * 根据销售订单加载没有创建采购订单的产品
     * @param orderId
     * @return
     */
    public List<SaleProductBean> loadNoPurchaseProductByOrderId(Integer orderId) {
        return orderDao.loadNoPurchaseProductByOrderId(orderId);
    }
    
    /**
     * 获得销售订单详情
     * @author suoyao.shen
     * @param id
     * @return
     */
    public SaleOrderBean getOrderDetail(Integer id) {
        return orderDao.getOrderDetail(id);
    }
    
    /**
     * 批量增加产品信息
     * @author suoyao.shen
     * @param orderId
     * @param pname
     * @param pattern
     */
    public void saveProductBatch(List<SaleProductBean> productList) {
        orderDao.saveOrderProductBatch(productList);
    }
    
    /**
     * 删除产品信息
     * @author suoyao.shen
     * @param productId
     */
    public void removeProduct(Integer[] productId, Integer orderId) {
        if (productId != null && productId.length > 0) {
            orderDao.removeProduct(Arrays.asList(productId));
        }
        //检查该销售订单下是否还有产品，如果没有产品的话，就删除订单
        int productCount = orderDao.getProductCountByOrderId(orderId).intValue();
        if (productCount == 0) {
            orderDao.removeOrderById(orderId);
        }
    }
    
    /**
     * 检查是否有销售订单号
     * @param orderNumber
     * @return
     */
    public boolean checkHasOrderNumber(String orderNumber) {
        Integer count = orderDao.queryOrderNumberCount(orderNumber);
        return count.intValue() > 0;
    }
    
    /**
     * 删除订单，并同时删除订单下的所有产品
     * @param orderId
     */
    public void removeOrder(Integer orderId) {
        //删除订单下的所有产品
        orderDao.removeProductByOrderId(orderId);
        //删除订单
        orderDao.removeOrderById(orderId);
    }
    
    /**
     * 导入销售订单Excel
     * @param order
     * @param excelPath
     * @return
     * @throws Exception
     */
    public int importOrder(SaleOrderBean order, String excelPath) throws Exception {
        try {
            /*
             * 1、打开一个Excel文件
             */
            HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(excelPath));
            List<SaleProductBean> productList = new ArrayList<SaleProductBean>();
            /*
             * 2、获得指定的sheet
             */
            HSSFSheet sheet = workbook.getSheetAt(0);
            //获得sheet总行数
            int rowCount = sheet.getLastRowNum();
            if (rowCount < 1) {
                /*
                 * 这里表示sheet里面没有行
                 */
            }
            /*
             * 3、遍历行row
             */
            for (int rowIndex = 1; rowIndex <= rowCount; rowIndex++) {
                //获得行对象
                HSSFRow row = sheet.getRow(rowIndex);
                if (null != row) {
                    //获得本行中单元格的个数
                    //int cellCount = row.getLastCellNum();
                    String _pname = getCellString(row.getCell(0));
                    String _pattern = getCellString(row.getCell(1));
                    String str_saleCount = getCellString(row.getCell(2));
                    Integer _saleCount = new Integer(StringUtil.isEmpty(str_saleCount) ? "0" : str_saleCount);
                    String str_salePrice = getCellString(row.getCell(3));
                    String _salePrice = StringUtil.isEmpty(str_salePrice) ? "0" : str_salePrice;
                    String str_totalPrice = getCellString(row.getCell(4));
                    String _totalPrice = StringUtil.isEmpty(str_totalPrice) ? "0" : str_totalPrice;
                    Date _deliverTime = DateUtil.parseDate(getCellString(row.getCell(5)), DateUtil.DATE_FORMAT);
                    String _remark = getCellString(row.getCell(6));
                    SaleProductBean product = new SaleProductBean(_pname, _pattern, _saleCount,
                            _salePrice, _totalPrice, _deliverTime, _remark);
                    //遍历列cell
                    /*for (short cellIndex = 0; cellIndex < cellCount; cellIndex++) {
                        HSSFCell cell = row.getCell(cellIndex);
                        //获得指定单元格中的数据
                        Object cellStr = getCellString(cell);
                        rowData.add(cellStr);
                    }*/
                    productList.add(product);
                }
            }
            SaleOrderBean orderBean = orderDao.saveOrder(order);
            for (SaleProductBean product : productList) {
                product.setOrderId(orderBean.getId());
            }
            saveProductBatch(productList);
            return orderBean.getId();
        } catch (FileNotFoundException e) {
            LOG.error("import excel error.", e);
            throw new Exception(e);
        } catch (IOException e) {
            LOG.error("import excel error.", e);
            throw new Exception(e);
        }
    }
    
    /**
     * @param cell
     * @return
     */
    private String getCellString(HSSFCell cell) {
        Object result = null;
        if (cell != null) {
            //单元格类型：Numeric:0,String:1,Formula:2,Blank:3,Boolean:4,Error:5
            int cellType = cell.getCellType();
            switch (cellType) {
                case HSSFCell.CELL_TYPE_STRING:
                    result = cell.getRichStringCellValue().getString();
                    break;
                case HSSFCell.CELL_TYPE_NUMERIC:
                    /*
                     * 这里是转换日期格式的
                     */
                    if(HSSFDateUtil.isCellDateFormatted(cell)) {
                        Date date = cell.getDateCellValue();
                        result = DateUtil.formateDate(date, DateUtil.DATE_FORMAT);
                    } else {
                        DecimalFormat df = new DecimalFormat("########");
                        result = df.format(cell.getNumericCellValue());
                    }
                    break;
                case HSSFCell.CELL_TYPE_FORMULA:
                    result = cell.getNumericCellValue();
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN:
                    result = cell.getBooleanCellValue();
                    break;
                case HSSFCell.CELL_TYPE_BLANK:
                    result = null;
                    break;
                case HSSFCell.CELL_TYPE_ERROR:
                    result = null;
                    break;
                default:
                    LOG.error("枚举了所有类型");
                    break;
            }
        }
        return result == null ? "" : result.toString();
    }
    
}
